﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using ASBCC.Database.Entity;
using SourceCode.Workflow.Client;
using ASBCC.Database.Service;

namespace ASBCC.Workflow.K2Manager
{
    public class SubmitActionHandler : ActionHandlerBase
    {
        #region Constructor

        public SubmitActionHandler(SerializableDictionary dataFields, K2AppForm appForm, K2WorkItem workItem, K2ActionInfo actionInfo, string comment, K2AuditDestination auditDestination, List<K2User> outputDestinationUsers) :
            base(dataFields, appForm, workItem, actionInfo, comment, auditDestination, outputDestinationUsers)
        {
            workItem.ArrvialDate = DateTime.Now;
            appForm.DelegateFrom.UserId = appForm.Applicant.UserId;
            appForm.DelegateFrom.UserEn = appForm.Applicant.UserEn;
            appForm.DelegateFrom.UserCn = appForm.Applicant.UserCn;
        }

        #endregion

        #region Override Methods
        //protected override string ActionName
        //{
        //    get
        //    {
        //        return K2ActionName.Action_Submit;
        //    }
        //}

        //protected override string ActionType
        //{
        //    get
        //    {
        //        return K2ActionType.Submit;
        //    }
        //}

        /// <summary>
        /// 执行流程动作
        /// 提交的流程执行过程比较特殊，需要重载
        /// </summary>
        protected override void ExcuteAction()
        {
            bool validated = this.ValidateAuditDestination(AuditDestination);
            if (!validated)
            {
                string message = string.Empty;
                if (AuditDestination != null) message = AuditDestination.ExportText();
                throw new Exception("Invalid AuditDestination. " + message);
            }

            Connection connection = K2Client.OpenConnection();
            try
            {
                SourceCode.Workflow.Management.WorklistItems worklistItems = K2Admin.GetWorklistItems(ProcessName, AppForm.Folio);
                if (worklistItems.Count == 0)
                {
                    //启动流程
                    _procInstID = K2Client.StartProcessInstance(connection, ProcessName, AppForm.Folio, AppForm.Applicant.UserId, this.DataFields);
              

                //提交到下一个节点
                worklistItems = K2Admin.GetWorklistItems(ProcessName, AppForm.Folio);

                SourceCode.Workflow.Management.WorklistItem worklistItem = worklistItems[0];

                //K2Admin.RedirectWorklistItem(worklistItem.Destination, K2Helper.GetAdminDestinationName(), worklistItem.ProcInstID, worklistItem.ActInstDestID, worklistItem.ID);
                string username = K2Helper.GetAuditUsername(worklistItem.Destination);
                connection.ImpersonateUser(username);
                
                string serialNumber = K2Helper.GetSerialNumber(worklistItem.ProcInstID, worklistItem.ActInstDestID);
                K2Client.ExecuteAction(connection, serialNumber, K2ActionName.Submit, AuditDestination, DataFields);

                connection.RevertUser();

                WorkItem.ProcInstId = _procInstID;
                }
                else
                {
                    if (worklistItems.Count != 1) throw new Exception(string.Format("ProcessInstance has been started. ProcessName={0};Filio={1};worklistItems.Count={2}", ProcessName, AppForm.Folio, worklistItems.Count));
                    _procInstID = worklistItems[0].ProcInstID;
                    return;
                }
            }
            finally
            {
                connection.Close();
            }
        }

        /// <summary>
        /// Submit动作时,重载图章生成方法,不需要生成图章
        /// </summary>
        protected override void BuildProcessStamp()
        {
        }

        protected override void SendMail()
        {
            string actionType = GetActionType();
            string ApplicationNameEn = FlowProcess.ProcDisplayEn;
            string ApplicationNameCn = FlowProcess.ProcDisplayCn;

            Flow_ProcessMailConfigTableEntity mailConfig = K2DataHelper.GetProcessMailConfig(WorkItem.ProcName, WorkItem.ActivityName, actionType);
            if (mailConfig == null) return;

            EZVisitApplicationTableEntity entity = EZVisitApplicationManager.SelectByKeys(AppForm.FormId);
            if (entity == null) return;

            // 通知下一步审批人
            if (NewMyActivityList != null && NewMyActivityList.Count > 0)
            {
                foreach (MyActivityTableEntity myActivity in NewMyActivityList)
                {
                    if (myActivity.OwnerID == K2User.TempUser) continue; //临时用户不需要通知

                    int toAuditorTemplate = mailConfig.ToAuditorTemplate ?? 0;
                    if (toAuditorTemplate <= 0) continue;

                    EmployeeTableEntity ownerInfo = K2DataHelper.GetUserInfoById(myActivity.OwnerID ?? 0);
                    if (!CheckMailApproverRule(ownerInfo)) continue;

                    string[] mailAddressArr = new string[] { ownerInfo.Email };
                    NameValueCollection collection = new NameValueCollection();
                    collection["{EnglishName}"] = myActivity.OwnerEn;
                    collection["{ChineseName}"] = myActivity.OwnerCn;
                    if (!entity.EZVisitReqNoIsNull())
                        collection["{SerialNumber}"] = entity.EZVisitReqNo;
                    else
                        collection["{SerialNumber}"] = myActivity.ApplicationNo;

                    collection["{SubmitterEN}"] = entity.RequesterNameEN;
                    collection["{SubmitterCN}"] = entity.RequesterNameCN;
                    collection["{FormURL}"] = myActivity.FormURL;

                    NameValueCollection titleCollection = new NameValueCollection();
                    if (entity.EZVisitReqNoIsNull())
                        if (!entity.EZVisitReqNoIsNull())
                            titleCollection["{SerialNumber}"] = entity.EZVisitReqNo;
                        else
                            titleCollection["{SerialNumber}"] = myActivity.ApplicationNo;

                    MailService.MailSender(mailAddressArr, toAuditorTemplate, collection, titleCollection);
                }
            }
        }

        protected override string GetActionType()
        {
            return K2ActionType.Submit;
        }

        #endregion
    }
}
